package cn.stylefeng.guns.modular.kh.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicPutgoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderPut;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderOutParam;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderPutParam;
import cn.stylefeng.guns.modular.kh.entity.KhOrderOut;
import cn.stylefeng.guns.modular.kh.model.params.DownDpsIby;
import cn.stylefeng.guns.modular.kh.model.params.KhOrderOutParam;
import cn.stylefeng.guns.modular.kh.service.KhOrderOutItemService;
import cn.stylefeng.guns.modular.kh.service.KhOrderOutService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.result.DictResult;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 提总订单控制器
 *
 * @author zzh
 * @Date 2025-10-21 15:06:17
 */
@Controller
@RequestMapping("/khOrderOut")
public class KhOrderOutController extends BaseController {

    private String PREFIX = "/kh/khOrderOut";

    @Autowired
    private KhOrderOutService khOrderOutService;

    @Autowired
    private KhOrderOutItemService khOrderOutItemService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private UserService userService;

    @Autowired
    private BasicPutgoodsService basicPutgoodsService;

    @Autowired
    private DictService dictService;

    private Lock lock = new ReentrantLock();

    /**
     * 跳转到主页面
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("")
    public String index(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));

        return PREFIX + "/khOrderOut.html";
    }

    /**
     * 新增页面
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/add")
    public String add(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));

        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));

        return PREFIX + "/khOrderOut_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/edit")
    public String edit(Model model) {
        return PREFIX + "/khOrderOut_edit.html";
    }

    /**
     * 新增接口
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(KhOrderOutParam khOrderOutParam) {
        User user = userService.getcurrentUser();
        if(ToolUtil.isNotEmpty(khOrderOutParam.getCustomerId())){
            BasicCustomer basicCustomer = basicCustomerService.getById(khOrderOutParam.getCustomerId());
            if(ToolUtil.isNotEmpty(basicCustomer)){
                khOrderOutParam.setCustomerName(basicCustomer.getCustomerName());
            }

        }
        khOrderOutParam.setOrderState("待提交");

        if(ToolUtil.isNotEmpty(khOrderOutParam.getSetWarehouseId())){
            BasicWarehouse basicWarehouse = basicWarehouseService.getById(khOrderOutParam.getSetWarehouseId());
            if(ToolUtil.isNotEmpty(basicWarehouse)){
                khOrderOutParam.setSetWarehouse(basicWarehouse.getWarehouseName());
            }
        }
        // 单位信息
        if(ToolUtil.isNotEmpty(khOrderOutParam.getGetUnitId())){
            BasicPutgoods basicPutgoods = basicPutgoodsService.getById(khOrderOutParam.getGetUnitId());
            if(ToolUtil.isNotEmpty(basicPutgoods)){
                khOrderOutParam.setGetUnitNumber(basicPutgoods.getUnitNumber());
            }
        }

        khOrderOutParam.setCreateUserName(user.getName());

        this.khOrderOutService.add(khOrderOutParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(KhOrderOutParam khOrderOutParam) {
        this.khOrderOutService.update(khOrderOutParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/delete")
    @ResponseBody
    @Transactional
    public ResponseData delete(KhOrderOutParam khOrderOutParam) {
        KhOrderOut khOrderOut = this.khOrderOutService.getById(khOrderOutParam.getId());
        if(!"待提交".equals(khOrderOut.getOrderState())){
            return ResponseData.error("只有【待提交】才能删除操作");
        }
        if(ToolUtil.isNotEmpty(khOrderOut.getDpsDownTime())){
            return ResponseData.error("已下发dps，无法删除");
        }
        Map<String,Object> delMap = new HashMap<>();
        delMap.put("order_out_number",khOrderOut.getOrderOutNumber());
        this.khOrderOutItemService.removeByMap(delMap);
        this.khOrderOutService.delete(khOrderOutParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(KhOrderOutParam khOrderOutParam) {
        KhOrderOut detail = this.khOrderOutService.getById(khOrderOutParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(KhOrderOutParam khOrderOutParam,String condition ) {

        if(ToolUtil.isEmpty(khOrderOutParam.getTimeType())){
            khOrderOutParam.setTimeType("cj");
        }

        if(ToolUtil.isEmpty(khOrderOutParam.getStartTime())){
            khOrderOutParam.setStartTime(DateUtil.getDate());
        }
        if(ToolUtil.isEmpty(khOrderOutParam.getEndTime())){
            khOrderOutParam.setEndTime(DateUtil.getDate());
        }
        return this.khOrderOutService.findPageBySpec(khOrderOutParam,condition);
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        //查询可选择仓库
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/import.html";
    }

    /**
     * 上传excel
     */
    @RequestMapping(value = "/importExceNewmethodl" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file, KhOrderOutParam khOrderOutParam)  {
        ResponseData data = new ResponseData();
        if(khOrderOutParam.getSetWarehouseId()==null||khOrderOutParam.getCustomerId()==null) {
            data.setSuccess(false);
            data.setMessage("请填写订单基本信息!");
            return data;
        }
        lock.lock();//获取锁
        try {
            data = khOrderOutService.getExceldata(file,khOrderOutParam,data);//处理导入数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return data;
    }


    /**
     * 导入页面
     */
    @RequestMapping("/toKhimportExcel")
    public String toKhimportExcel(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        //查询可选择仓库
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/importKh.html";
    }

    /**
     * 上传excel
     */
    @RequestMapping(value = "/importKhExceNewmethodl" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importKhExceNewmethodl(@RequestPart("file") MultipartFile file, KhOrderOutParam khOrderOutParam)  {
        ResponseData data = new ResponseData();
        if(khOrderOutParam.getSetWarehouseId()==null||khOrderOutParam.getCustomerId()==null) {
            data.setSuccess(false);
            data.setMessage("请填写订单基本信息!");
            return data;
        }
        lock.lock();//获取锁
        try {
            data = khOrderOutService.getKhExceldata(file,khOrderOutParam,data);//处理导入数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return data;
    }


    @RequestMapping("/toDownDps")
    public String toDownDps(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        List<DictResult> waveNumList = this.dictService.findByDicttypeCode2("KH_BC");
        model.addAttribute("waveNumList", waveNumList);
        return PREFIX + "/downDps.html";
    }

    /**
     * 下发DPS
     * @param downDpsIby
     * @return
     */
    @RequestMapping(value = "/downDps" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData downDps(DownDpsIby downDpsIby)  {
        if(ToolUtil.isEmpty(downDpsIby.getWaveNum())) {
            return ResponseData.error("请选择波次！");
        }
        if(ToolUtil.isEmpty(downDpsIby.getWorkType())) {
            return ResponseData.error("请选择模式！");
        }
        if(ToolUtil.isEmpty(downDpsIby.getSetWarehouseId())) {
            return ResponseData.error("请选择仓库！");
        }
        if(ToolUtil.isEmpty(downDpsIby.getOrderType())) {
            return ResponseData.error("请选择单据类型！");
        }
        try {
            return khOrderOutService.downDps(downDpsIby);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error(e.getMessage());
        }
    }

    /**
     * 下载入库订单模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelTemplate")
    public void downloadExcelTemplate(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
        String path = "assets/excel/khorderOut.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("提总出库订单模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载入库订单模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadKhExcelTemplate")
    public void downloadKhExcelTemplate(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
        String path = "assets/excel/khTzorderOut.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("可好提总出库订单模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量作废
     */
    @RequestMapping("/gxTz")
    @ResponseBody
    public ResponseData gxTz(@RequestParam("ids") Long[] ids) {
        if(ToolUtil.isEmpty(ids)){
            return ResponseData.error("请选择要提总的订单");
        }

        try {
            return khOrderOutService.gxTz(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error(e.getMessage());
        }
    }

}


